package com.dora.basic.basic;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 人名比较器
 *
 * @author hanchen
 * @date 2024/02/20
 */
public class PersonNameComparator implements Comparator<Person> {
    @Override
    public int compare(Person p1, Person p2) {
        return p1.getName().compareTo(p2.getName());
    }

    @Test
    public void compare() {
        List<Person> people = new ArrayList<>();
        people.add(new Person("Alice", 30));
        people.add(new Person("Bob", 25));
        people.add(new Person("Charlie", 35));

        // 使用 Comparable 接口默认的比较规则进行排序（按年龄）
        Collections.sort(people);
        System.out.println("按年龄排序:");
        for (Person person : people) {
            System.out.println(person);
        }

        // 制定使用 Comparator 进行按姓名排序
        Collections.sort(people, new PersonNameComparator());
        System.out.println("\n按姓名排序:");
        for (Person person : people) {
            System.out.println(person);
        }
    }
}
